/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sUtils;

import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author thomas.s
 */

public class VolumeKeys extends TimerTask {

    Timer timer = null;
    VolumeControl vc = null;
    EventListener ev = null;
    int first=0, last=0;
    boolean active=true;

    public VolumeKeys( EventListener parent )
    {
        ev = parent;
        InputStream is = getClass().getResourceAsStream("/sonar.mp3");
        Player player=null;
        try {
            player = Manager.createPlayer(is, "audio/mp3");
            player.realize();
            vc = (VolumeControl)player.getControl("VolumeControl");
            last = first = vc.getLevel();
            if (last==0) last=5; else if (last==100) last=95;
        } catch(Exception e){}
        if (vc!=null)
        {
            reset();
            timer = new Timer();
            timer.schedule(this, 50, 50 );
        }
    }

    public void reset()
    {
        vc.setLevel(last);
        last = vc.getLevel();
    }

    public void run()
    {
        int vol = vc.getLevel();
        if (vol!=last && active)
        {
            ev.onEvent( "volume", vol>last ? "+1" : "-1");
            reset();
        }
    }

    public void stop()
    {
        if (timer!=null)
        {
            timer.cancel();
            timer = null;
        }
    }

    public int getLevel() { return vc.getLevel(); }
    public void setActive( boolean on ) { active=on; }

    public void mute( boolean on )
    {
        if (on) active = false;
        vc.setLevel( on?0:last );
        if (!on) active = true;
    }


}
